package com.cms.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.cms.common.util.StringUtil;


/** 
 * 客户端(浏览器)缓存控制过滤器（对于支付相关请求，应设置为不缓存）.
 * 
 * <p>在web.xml中的配置如下：</p>
 * <pre style="color:green;background:#ccc;">
 * &lt;filter&gt;
 * 	&lt;filter-name&gt;cacheControlFilter&lt;/filter-name&gt;
 * 	&lt;filter-class&gt;fuc.common.filter.CacheControlFilter&lt;/filter-class&gt;
 * 	&lt;init-param&gt;
 * 		&lt;param-name&gt;expirationTime&lt;/param-name&gt;
 * 		&lt;param-value&gt;0&lt;/param-value&gt;
 * 	&lt;/init-param&gt;
 * &lt;/filter&gt;
 * &lt;filter-mapping&gt;
 * 	&lt;filter-name&gt;cacheControlFilter&lt;/filter-name&gt;
 * 	&lt;url-pattern&gt;/shop/order!info.action&lt;/url-pattern&gt;
 * &lt;/filter-mapping&gt;
 * &lt;filter-mapping&gt;
 * 	&lt;filter-name&gt;accessDeniedFilter&lt;/filter-name&gt;
 * 	&lt;url-pattern&gt;/shop/payment!submit.action&lt;/url-pattern&gt;
 * &lt;/filter-mapping&gt;</pre>
 */
public class CacheControlFilter implements Filter {
	/** 参数名 */
	private static final String EXPIRATION_TIME_PARAMETER_NAME = "expirationTime";
	/** 参数值（单位：秒，0表示不缓存） */
	private long expirationTime = 0;	//默认0
	
	
	/** 初始化 .*/
	public void init(FilterConfig filterConfig) {
		String expirationTimeParameter = filterConfig.getInitParameter(EXPIRATION_TIME_PARAMETER_NAME);
		if (expirationTimeParameter != null) {
			expirationTime = Long.valueOf(expirationTimeParameter);
		}
	}

	/** 过滤. */
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		if (!response.isCommitted()) {
			if (expirationTime > 0) {
				long timeMillis = System.currentTimeMillis() + expirationTime * 1000;
				response.setDateHeader("Expires", timeMillis);
				response.setHeader("Cache-Control",  StringUtil.join("private, max-age=", expirationTime));
			} else {
				response.setHeader("progma", "no-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setHeader("Cache-Control", "no-store");
				response.setDateHeader("Expires", 0);
			}
		}
		chain.doFilter(servletRequest, servletResponse);
	}

	/** 销毁. */
	public void destroy() {}

}